<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>My first three.js app</title>
		<style>
			html,body { margin: 0; height: 100%; }
      #c { width: 100%; height: 100%; display: block; }
		</style>
	</head>
	<body>
    <canvas id="c"></canvas>
		<script src="../js/three.js"></script>
		<script>
      const canvas = document.querySelector('#c')
      // 创建渲染器实例
      const renderer = new THREE.WebGLRenderer({canvas})

      // 相机
      const fov = 75
      const aspect = 2
      const near = 0.1
      const far = 5
      const camera = new THREE.PerspectiveCamera(fov, aspect, near, far)
      camera.position.z = 4


      // 场景
			const scene = new THREE.Scene()
      {
        const color = 0xFFFFFF
        const intensity = 1
        const light = new THREE.DirectionalLight(color, intensity)
        light.position.set(-1, 2, 4)
        scene.add(light)
      }

      // 创建立方体
      // 创建一个立方体对象
      const boxWidth = 1
      const boxHeight = 1
      const boxDepth = 1
      const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth)

      function makeInstance(geometry, color, x) {
        // 给立方体材质，颜色等
        const material = new THREE.MeshPhongMaterial({color})
        // 添加网格
        const cube = new THREE.Mesh(geometry, material)
        // 将网格放入到场景中
        scene.add(cube)
        // 摄像机默认指向 Z 轴负方向，上方向朝向Y轴正方向，我们需要往后移一下摄像机才能显示出物体
        cube.position.x = x
        return cube
      }

      const cubes = [
        makeInstance(geometry, 0x44aa88, 0),
        makeInstance(geometry, 0x8844aa, -2),
        makeInstance(geometry, 0xaa8844, 2)
      ]
      // 响应性设置 （1）
      // 检查渲染器的canvas 尺寸是不是和canvas的显示尺寸一样，如果不一样就设置它
      function resizeRendererToDisplaySize(renderer) {
        const canvas = renderer.domElement
        const width = canvas.clientWidth
        const height = canvas.clientHeight
        const needResize = canvas.width !== width || canvas.height !== height
        if (needResize) {
          // 设置 canvas 的绘图缓冲区
          renderer.setSize(width, height, false)
        }
        return needResize
      }
    
      // 渲染场景（渲染循环）
      function animate() {
        requestAnimationFrame(animate)

        // 响应性设置 （2）
        if (resizeRendererToDisplaySize(renderer)) {
          // 解决拉伸变形的问题
          const canvas = renderer.domElement
          camera.aspect = canvas.clientWidth / canvas.clientHeight
          camera.updateProjectionMatrix()
        }

        // 使立方体动起来
        cubes.forEach((cube, index) => {
          const speed = (index + 1) * 1
          cube.rotation.x += 0.01 * speed
          cube.rotation.y += 0.01 * speed
        })
        renderer.render(scene, camera)
      }
      animate()
		</script>
	</body>
</html>